package com.wxsong.authplatform.authweb.controller.role;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.wxsong.authplatform.authweb.util.Base64Util;
import com.wxsong.authplatform.authweb.util.ListResponse;
import com.wxsong.authplatform.authweb.util.Response;
import com.wxsong.authplatform.authweb.util.ResponseCode;
import com.wxsong.authplatform.authweb.controller.BaseController;
import com.wxsong.authplatform.authweb.controller.role.dto.RoleDTO;
import com.wxsong.authplatform.authweb.exception.InstantException;
import com.wxsong.authplatform.authweb.model.role.Role;
import com.wxsong.authplatform.authweb.service.role.RoleService;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/role")
public class RoleController extends BaseController {

    private Logger logger = LoggerFactory.getLogger(RoleController.class);

    @Resource
    private RoleService roleService;

    @RequestMapping(value = "/index")
    public String index() {
        return "role/index";
    }

    @RequestMapping(value = "/add_index")
    public String toAdd() {
        return "role/add";
    }

    @RequestMapping(value = "/update_index")
    public String toUpdate(ModelMap modelMap, String ids) {
        String id = Base64Util.decode(ids);
        Role role = roleService.getById(Long.parseLong(id));
        modelMap.put("role", role);
        modelMap.put("id", Base64Util.encode(role.getId() + ""));
        return "role/update";
    }

    @RequestMapping(value = "/list", method = RequestMethod.POST)
    @ResponseBody
    public Response list(RoleDTO roleDTO) {
        System.out.println(roleDTO);
        Map<String, Object> paramMap = Maps.newHashMap();
        List list = Lists.newArrayList();
        try {
            paramMap.put("name", roleDTO.getName());
            Long count = roleService.count(paramMap);
            if (count.compareTo(0l) > 0) {
                list = roleService.list(getFrom(roleDTO.getPage(), getSize(roleDTO.getRows())), getSize(roleDTO.getRows()), paramMap);
            }
            parseList(list);
            return ListResponse.success(count, list);
        } catch (Exception e) {
            logger.error("/role/list  error", e);
            return Response.fail(ResponseCode.FAIL.info);
        }

    }

    private void parseList(List<Role> list) {
        List tmp = Lists.newArrayList();
        for (Role role : list) {
            RoleDTO roleDTO = new RoleDTO();
            roleDTO.setId(Base64Util.encode(role.getId() + ""));
            roleDTO.setName(role.getName());
            tmp.add(roleDTO);
        }
        list.clear();
        list.addAll(tmp);
    }

    @RequestMapping(value = "/add", method = RequestMethod.POST)
    @ResponseBody
    public Response add(RoleDTO roleDTO) {
        Map resultMap = Maps.newHashMap();
        Role role = changeRole(roleDTO);
        try {
            check(role);
            int i = roleService.add(role);
            if (i < 1) {
                return Response.fail(ResponseCode.ADD_ROLE_FAIL);
            }
        } catch (InstantException e) {
            logger.error("/role/add  error", e);
            return Response.fail(ResponseCode.ADD_ROLE_FAIL.code, e.getMessage());
        } catch (Exception e) {
            logger.error("/role/add  error", e);
            return Response.fail(ResponseCode.ADD_ROLE_FAIL);
        }
        return Response.success(resultMap);
    }

    @RequestMapping(value = "/modify", method = RequestMethod.POST)
    @ResponseBody
    public Response modify(RoleDTO roleDTO) {
        Map resultMap = Maps.newHashMap();
        try {
            Long id = Long.parseLong(Base64Util.decode(roleDTO.getId()));
            Role role = roleService.getById(id);
            if (null == role) {
                throw new InstantException("角色不存在");
            }
            int c = roleService.updateInfo(id, roleDTO.getName());
            if (c < 0) {
                return Response.fail(ResponseCode.UPDATE_ROLE_FAIL);
            }
        } catch (InstantException e) {
            logger.error("/role/modify  error", e);
            return Response.fail(ResponseCode.UPDATE_ROLE_FAIL.code, e.getMessage());
        } catch (Exception e) {
            logger.error("/role/modify  error", e);
            return Response.fail(ResponseCode.UPDATE_ROLE_FAIL);
        }
        return Response.success(resultMap);
    }

    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    @ResponseBody
    public Response delete(String idStr) {
        Map resultMap = Maps.newHashMap();
        try {
            Long[] ids = decodeIds(idStr);
            int count = roleService.delete(ids);
            if (count < 0) {
                return Response.fail(ResponseCode.DELETE_ROLE_FAIL);
            }
        } catch (InstantException e) {
            logger.error("/role/delete  error", e);
            return Response.fail(ResponseCode.DELETE_ROLE_FAIL.code, e.getMessage());
        } catch (Exception e) {
            logger.error("/role/delete  error", e);
            return Response.fail(ResponseCode.DELETE_ROLE_FAIL.info);
        }
        return Response.success(resultMap);
    }

    @RequestMapping(value = "/auth_index")
    public String toAuth(ModelMap modelMap, String id) {
        id = Base64Util.decode(id);
        Long longId = Long.parseLong(id);
        Role role = roleService.getById(longId);
//        Long[] ids = ids(role.getAuths());
//        List<Authority> hasAuths = roleService.hasAuths(ids);
//        List<Authority> noAuths = roleService.noAuths(ids);
//        modelMap.put("has", hasAuths);
//        modelMap.put("no", noAuths);
//        modelMap.put("id", Base64Util.encode(role.getId() + ""));
        return "role/auth";
    }

    @RequestMapping(value = "/modifyAuth", method = RequestMethod.POST)
    @ResponseBody
    public Response modifyAuth(String ids, String roleId){
        Map resultMap = Maps.newHashMap();
        try {
            Subject subject = SecurityUtils.getSubject();
//            Users users = (Users)subject.getSession().getAttribute(Const.SESSION_USER_KEY);//操作人
            Role role = roleService.getById(Long.parseLong(Base64Util.decode(roleId)));
            if(null == role){
                throw new InstantException("被授权角色为空");
            }
//            ids = decodeIdsToString(ids);
            int count = roleService.modifyAuth(ids, role.getId());
            if (count < 0) {
                return Response.fail(ResponseCode.GRANT_ROLE_AUTH_FAIL);
            }
        }catch (InstantException e){
            logger.error("/role/modifyAuth  error", e);
            return Response.fail(ResponseCode.GRANT_ROLE_AUTH_FAIL.code, e.getMessage());
        }catch (Exception e){
            logger.error("/role/modifyAuth  error", e);
            return Response.fail(ResponseCode.GRANT_ROLE_AUTH_FAIL.info);
        }
        return Response.success(resultMap);
    }

    private boolean check(Role role) throws InstantException {
        if (StringUtils.isBlank(role.getName())) {
            throw new InstantException("参数不合法");
        }
        return true;
    }

    private Role changeRole(RoleDTO roleDTO) {
        String name = roleDTO.getName();
        Role role = new Role(name);
        return role;
    }
}


